package com.baozun.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;

import com.baozun.model.TChat;
import com.baozun.service.ChatService;
@Controller
public class ChatMessageController {
    
    @Autowired
    private ChatService chatService;
    // 用于转发数据(sendTo)
    @Autowired
    private SimpMessagingTemplate template;
    
    /**
     * WebSocket聊天的相应接收方法和转发方法 转发地址为jsp用于刷新jsp中信息
     * 
     * @param userChat 关于用户聊天的各个信息
     */
    @MessageMapping("/sendChat")
    public void sendChat(TChat chat) {
        // 找到需要发送的地址
        String address = chat.getAddress();
        String dest = address;
        syncSaveChat(chat);
        // 发送用户的聊天记录
        this.template.convertAndSend(dest, chat);
    }
    
    /**
     * 异步保存聊天记录
     * 
     * @param chat
     */
    @Async
    public void syncSaveChat(TChat chat) {
        chatService.add(chat);
    }
}
